package com.lianqi.emcpframework.ddd.gencode.plugin;

import java.lang.annotation.Annotation;

import javax.lang.model.element.TypeElement;

import com.lianqi.emcpframework.ddd.gencode.controller.*;
import com.lianqi.emcpframework.ddd.gencode.controller.parser.GenControllerMethodMetaParser;
import com.lianqi.emcpframework.ddd.gencode.controller.writer.GenControllerCreateMethodWriter;
import com.lianqi.emcpframework.ddd.gencode.controller.writer.GenControllerSelectMethodWriter;
import com.lianqi.emcpframework.ddd.gencode.controller.writer.GenControllerUpdateMethodWriter;
import com.lianqi.emcpframework.ddd.gencode.define.JavaSource;
import com.squareup.javapoet.TypeSpec;

public final class GenControllerPlugin extends AbstractProcessorPlugin {

    @Override
    public Class<Annotation>[] applyAnnCls() {
        return new Class[] {GenController.class};
    }

    @Override
    protected void process(TypeElement typeElement, Annotation annotation) {
        GenControllerMethodMetaParser methodMetaParser = new GenControllerMethodMetaParser(getTypeCollector());
        GenControllerAnnotationParser parser =
            new GenControllerAnnotationParser(typeElement, (GenController)annotation);

        JavaSource support = getJavaSourceCollector().getByName(parser.getControllerName());
        if (support == null) {
            TypeSpec.Builder supportBuilder = new GenControllerSupportBuilderFactory(parser.getTypeElement(),
                parser.getSimpleEndpointName(), parser.getParentName()).create();
            support = new JavaSource(parser.getPkgName(), parser.getSimpleEndpointName(), supportBuilder);
            getJavaSourceCollector().register(support);
        }

        GenControllerMethodMeta methodMeta = methodMetaParser.parse(parser.getTypeElement());

        new GenControllerCreateMethodWriter(parser, methodMeta.getCreateMethods(), this.getTypeCollector())
            .writeTo(support);
        new GenControllerUpdateMethodWriter(parser, methodMeta.getUpdateMethods(), this.getTypeCollector())
            .writeTo(support);
        new GenControllerSelectMethodWriter(parser, methodMeta.getQueryMethods(), getTypeCollector()).writeTo(support);

    }

    @Override
    public <A extends Annotation> Class<A>[] ignoreAnnCls() {
        return new Class[] {GenControllerIgnore.class};
    }
}
